package net.fireox.oa.comm.rtc.web;

import java.io.IOException;
import java.util.List;

import javax.servlet.AsyncContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.fireox.oa.comm.rtc.entity.RTCMessage;
import net.fireox.oa.comm.rtc.listener.RTCAsyncContextListener;
import net.fireox.oa.comm.rtc.store.RTCConnectionStore;
import net.fireox.oa.comm.rtc.store.RTCMessageStore;
import net.fireox.oa.util.json.JsonUtil;

/**
 * Servlet implementation class RTCServerServlet
 */
@WebServlet(urlPatterns="/comm/RTCServerServlet", asyncSupported=true)
public class RTCServerServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public RTCServerServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String key = "zhujingjun";
		
		@SuppressWarnings("unchecked")
		List<RTCMessage> msgs = (List<RTCMessage>) RTCMessageStore.getMessages(key);
		
		if(msgs!=null&&msgs.size()>0){
			response.getWriter().print(JsonUtil.encode(msgs));
			response.getWriter().flush();
		}else{
			AsyncContext context = request.startAsync(request, response);

			context.setTimeout(10*1000);
			
			context.addListener(new RTCAsyncContextListener(key));
			
			RTCConnectionStore.put(key, context);
		}
	}

}
